<template>
  <div
    v-loading="loading"
    class="app-container uni-scroll"
    style="height: calc(100vh - 100px);"
  >
    <div>
      <el-button-group style=";margin-right: 5px">
        <el-button
          round
          type="primary"
          @click="searchDay"
        >24{{ $t('hour') }}
        </el-button>
        <el-button
          type="primary"
          @click="searchWeek"
        >{{ $t('one') + $t('week') }}
        </el-button>
        <el-button
          type="primary"
          @click="searchMonth"
        >{{ $t('one') + $t('month') }}
        </el-button>
        <el-button
          type="primary"
          @click="search3month"
        >{{ $t('three') + $t('month') }}
        </el-button>
      </el-button-group>

      <el-date-picker
        v-model="startDate"
        style=";margin-right: 5px"
        type="datetime"
        :placeholder="$t('startDate')"
        align="right"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-date-picker
        v-model="endDate"
        style=";margin-right: 5px"
        type="datetime"
        :placeholder="$t('endDate')"
        align="right"
        :picker-options="pickerOptions1"
        value-format="timestamp"
      />
      <el-button-group>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="listSensor"
        >{{ $t('search') }}
        </el-button>
      </el-button-group>
    </div>
    <div v-for="(sensor,sensorIndex) in sensorList" :key="sensorIndex">
      <div
        v-if="sensor.canvasList && sensor.canvasList.length > 0"
        class="primary-color"
        style="line-height: 40px;font-size:15px;margin-left: 13px"
      >
        {{ sensor.sensorName }}
        <span style="color: #34bfa3;margin-left: 13px">[{{ formatSensorType(sensor.type) }}{{
            $t('port')
          }}:{{ sensor.port }}]</span>
      </div>
      <el-row :gutter="2">
        <el-col
          v-for="(item,index) in sensor.canvasList"
          :key="index"
          :xs="item.zooMax ? 24 : 12"
          :sm="item.zooMax ? 24 : 12"
          :md="item.zooMax ? 16 : 8"
          :lg="item.zooMax ? 16 : 8"
          :xl="item.zooMax ? 16 : 8"
        >
          <div
            v-if="item.type!=='hidden' && (showHidden === '1' || !item.hidden)"
            class="box-card item"
            style="margin-top: 5px"
          >
            <div style="margin: 0 20px;display: flex;justify-content: space-between">
              <div style="display: flex">
                <device-explain-icon :explain="item"/>
                <div style="flex-grow: 1;margin-left: 5px">
                  <div style="font-size:12px;font-weight: lighter;line-height: 15px">
                    <span class="primary-color;">{{ item.name }}</span>
                    <span
                      v-if="enableEval === '1' ? item.value.length < 6 : item.rawValue.length < 6"
                      style="float: right;color: #909399;"
                    >{{ enableEval === '1' ? item.value + item.unit : item.rawValue + item.unit }}</span>
                    <i
                      v-if="enableEval === '1' && item.value != '' && !isNaN(Number(item.value)) && item.lastValue != '' && !isNaN(Number(item.lastValue))"
                      :class="item.value > item.lastValue ? 'el-icon-top':'el-icon-bottom'"
                    />
                    <i
                      v-else-if="item.rawValue != '' && !isNaN(Number(item.rawValue)) && item.lastRawValue != '' && !isNaN(Number(item.lastRawValue))"
                      :class="item.rawValue > item.lastRawValue ? 'el-icon-top':'el-icon-bottom'"
                    />
                  </div>
                  <div style="font-size:13px;color: #909399;">{{ formatDate(item.valueDate) }}</div>
                </div>
              </div>
              <el-button-group>
                <el-button
                  icon="el-icon-more"
                  @click="explainInfo(item)"
                />
                <el-button
                  v-if="!item.zooMax"
                  icon="el-icon-full-screen"
                  @click="zooMax(item)"
                />
                <el-button
                  v-else
                  icon="el-icon-crop"
                  @click="zooMin(item)"
                />
                <el-button
                  v-if="showSort && !item.hidden"
                  type="danger"
                  icon="el-icon-close"
                  @click="hiddenExplain(item)"
                />
                <el-button
                  v-else-if="showSort"
                  icon="el-icon-view"
                  @click="showExplain(item)"
                />
              </el-button-group>
            </div>
            <line-chart v-if="item.type === 'line'" :chart-data="item" style="width: 100%;height:300px "/>
            <multi-line-chart
              v-else-if="item.type === 'line:multi'"
              style="height: 300px;width: 100%;"
              :chart-data="item.data"
            />
            <el-table
              v-else
              :data="item.data"
              style="width: 94%;margin: 0 auto"
              height="300"
              :show-header="false"
            >
              <el-table-column prop="value"/>
              <el-table-column prop="date"/>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top: 13px;margin-left: 25px">
      <el-switch
        v-model="filterRepeat"
        style=";margin-right: 5px"
        active-value="1"
        inactive-value="0"
        :active-text="$t('filter')+$t('repeat')"
        @change="filterRepeatChange"
      />
      <el-switch
        v-model="enableEval"
        active-value="1"
        inactive-value="0"
        :active-text="$t('enable')+$t('script')"
        @change="enableEvalChange"
      />
      <el-switch
        v-model="showHidden"
        active-value="1"
        inactive-value="0"
        :active-text="$t('show') + $t('hidden')"
        @change="showHiddenChange"
      />
      <el-switch
        v-model="addFrame"
        active-value="1"
        inactive-value="0"
        :active-text="$t('add')+$t('frame')"
        @change="addFrameChange"
      />
    </div>

    <el-dialog
      :title="explain.name"
      :visible.sync="dialogExplainInfoFormVisible"
      width="1300px"
      top="50px"
    >
      <device-explain-info v-if="dialogExplainInfoFormVisible" :explain="explain"/>
    </el-dialog>

    <el-dialog
      :visible.sync="showSetting"
      :title="deviceName"
      width="1200px"
      top="15px"
    >
      <device-setting
        :device-core="deviceCore"
        class="uni-scroll"
        style="height: 600px"
      />
    </el-dialog>

    <el-button
      icon="el-icon-setting"
      circle
      type="primary"
      style="position: fixed;bottom: 30px;right: 20px;z-index: 1000"
      @click="deviceSetting"
    />

  </div>
</template>

<script>
import LineChart from '@/components/Chart/LineChart'
import { failureNotice, formatDate, formatSensorType } from '@/util/common'
import { listSensor } from '@/api/iot/iotDeviceSensorApi'
import { listWithExplain } from '@/api/iot/iotDeviceSensorDataApi'
import { updateExplain } from '@/api/iot/iotDeviceExplainApi'
import DeviceSetting from '@/components/DeviceSetting'
import DeviceExplainInfo from '@/components/DeviceExplainInfo'
import resize from '@/components/Mixins/resize'
import {
  getAddFrame,
  getEnableEval,
  getFilterRepeat,
  getLanguage,
  getShowHidden,
  setAddFrame,
  setEnableEval,
  setFilterRepeat,
  setShowHidden
} from '@/util/storage'
import DeviceExplainIcon from '@/components/DeviceExplainIcon'
import MultiLineChart from '@/components/Chart/MultiLineChart'

export default {
  name: 'SensorHistory',
  components: {
    DeviceExplainIcon,
    LineChart,
    DeviceExplainInfo,
    DeviceSetting,
    MultiLineChart
  },
  mixins: [resize],
  data() {
    return {
      showSort: false,
      dialogExplainInfoFormVisible: false,
      language: getLanguage(),
      deviceName: null,
      deviceCore: null,
      startDate: '',
      endDate: '',
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },

      explain: {},
      tempRoute: {},
      showSetting: false,
      sensorList: [],
      loading: false,
      filterRepeat: getFilterRepeat(),
      enableEval: getEnableEval(),
      showHidden: getShowHidden(),
      addFrame: getAddFrame()
    }
  },
  mounted() {
    const param = this.$route.query
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName

    const timestamp = new Date().getTime() + 5 * 60 * 60 * 1000
    this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
    this.endDate = timestamp

    this.listSensor()
    if (!this.deviceName) {
      this.deviceName = this.deviceCore
    }
    this.setTagsViewTitle()
  },
  methods: {
    zooMax(item) {
      const type = item.type
      item.type = 'hidden'
      this.$nextTick(() => {
        item.type = type
        item.zooMax = true
      })
    },
    zooMin(item) {
      const type = item.type
      item.type = 'hidden'
      this.$nextTick(() => {
        item.type = type
        item.zooMax = false
      })
    },
    hiddenExplain(item) {
      const hidden = true
      const json = {
        hidden: hidden,
        explainId: item.explainId
      }
      updateExplain(json).then(res => {
        const { code } = res
        if (code === '200') {
          item.hidden = hidden
        }
      })
    },
    showExplain(item) {
      const hidden = false
      updateExplain({
        explainId: item.explainId,
        hidden: hidden
      }).then(res => {
        const { code } = res
        if (code === '200') {
          item.hidden = hidden
        }
      })
    },
    explainInfo(index) {
      this.explain = index
      this.dialogExplainInfoFormVisible = true
    },
    filterRepeatChange() {
      setFilterRepeat(this.filterRepeat)
      this.listSensor()
    },
    enableEvalChange() {
      setEnableEval(this.enableEval)
      this.listSensor()
    },
    showHiddenChange() {
      setShowHidden(this.showHidden)
    },
    addFrameChange() {
      setAddFrame(this.addFrame)
    },
    formatSensorType(type) {
      return formatSensorType(this, type)
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    deviceSetting() {
      this.showSetting = true
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },

    listSensor() {
      this.loading = true
      listSensor({
        deviceCore: this.deviceCore
      }).then(res => {
        const { data, code } = res
        this.sensorList = []
        if (code === '200') {
          data.forEach(sensor => {
            this.listWithExplain(sensor)
          })
        }
        this.loading = false
      })
    },
    listWithExplain(sensor) {
      listWithExplain({
        // dbType: 'taos',
        sensorId: sensor.sensorId,
        startTime: Math.round(this.startDate / 1000),
        endTime: Math.round(this.endDate / 1000),
        enableEval: this.enableEval === '1',
        filterRepeat: this.filterRepeat === '1'
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          const dataList = data.dataList
          if (data.explainList == null) {
            failureNotice(this, this.$t('no') + this.$t('explain'))
            return
          }

          /**
           * 装换时间
           */

          for (let i = 0, j = dataList.length; i < j; i++) {
            const commonTime = formatDate(this, dataList[i].createdTime)
            dataList[i].createdTime = commonTime

            const val = dataList[i].val
            val.createdTime = commonTime
          }
          const canvasList = []
          const explainLastValueMap = {}
          for (let i = 0, j = data.explainList.length; i < j; i++) {
            const explain = data.explainList[i]
            const item = {
              ...explain,
              index: i,
              zooMax: false
            }
            if (explain.type === 'static' || explain.type === 'static:multi') {
              continue
            }
            if (explain.type === 'line') {
              const dy = []
              const dx = []

              let dataBean
              for (let k = 0, l = dataList.length; k < l; k++) {
                const dataItem = dataList[k]
                dataBean = dataItem.val
                if (typeof (dataBean[explain.keyName]) !== 'undefined') {
                  explainLastValueMap[explain.keyName] = dataBean[explain.keyName]
                  dy.push(dataBean[explain.keyName])
                  dx.push(dataItem.createdTime)
                } else if (this.addFrame === '1') {
                  dy.push(explainLastValueMap[explain.keyName] || this.enableEval === '1' ? explain.value : explain.rawValue)
                  dx.push(dataItem.createdTime)
                }
              }

              item.dataList = dy
              item.dateList = dx
              canvasList.push(item)
            } else if (explain.type === 'line:multi') {
              let dataBean
              const xList = []
              const yList = []
              for (let k = 0, l = dataList.length; k < l; k++) {
                dataBean = dataList[k].val
                if (typeof (dataBean[explain.keyName]) !== 'undefined') {
                  xList.push(dataList[k].createdTime)
                  const valList = dataBean[explain.keyName].split(',')
                  for (let n = 0, m = valList.length; n < m; n++) {
                    const yd = valList[n]
                    let have = false
                    for (const yItem of yList) {
                      if (yItem.name === n) {
                        yItem.dataList.push(yd)
                        have = true
                        break
                      }
                    }
                    if (!have) {
                      yList.push({
                        name: n,
                        unit: explain.unit,
                        dataList: [yd]
                      })
                    }
                  }
                }
              }
              item.data = {
                dateList: xList,
                dataList: yList
              }
              canvasList.push(item)
            } else {
              const data = []
              for (let k = 0, l = dataList.length; k < l; k++) {
                const dataBean = dataList[k].val
                if (typeof (dataBean[explain.keyName]) !== 'undefined') {
                  data.push({
                    value: dataBean[explain.keyName],
                    date: dataList[k].createdTime
                  })
                }
              }
              item.data = data
              canvasList.push(item)
            }
          }

          this.sensorList.push({
            ...sensor,
            canvasList: canvasList
          })
        }
      })
    },
    search3month() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 3 * 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listSensor()
    },
    searchMonth() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 31 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listSensor()
    },
    searchDay() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listSensor()
    },
    searchWeek() {
      const timestamp = new Date().getTime()
      this.startDate = new Date().getTime() - 7 * 24 * 60 * 60 * 1000
      this.endDate = timestamp
      this.listSensor()
    }
  }
}
</script>
<style scoped lang="scss">
@import '@/styles/element-variables.scss';

.primary-color {
  color: $--color-primary;
}

.item {
  height: 353px;
}

.item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  border-radius: 12px;
}

</style>
